<template>
  <div class="material-management">
    <!-- 页面标题和操作按钮 -->
    <div class="page-header">
      <div class="header-left">
        <h2>物料管理</h2>
        <p class="page-description">管理物料档案信息，包括分类、规格、供应商和价格等</p>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="showAddDialog" :icon="Plus">
          新增物料
        </el-button>
        <el-button @click="exportMaterial" :icon="Download">
          导出物料
        </el-button>
        <el-button @click="importMaterial" :icon="Upload">
          导入物料
        </el-button>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <div class="search-section">
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="物料名称">
          <el-input
            v-model="searchForm.materialName"
            placeholder="请输入物料名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="物料编号">
          <el-input
            v-model="searchForm.materialCode"
            placeholder="请输入物料编号"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="物料分类">
          <el-select v-model="searchForm.category" placeholder="请选择分类" clearable style="width: 150px">
            <el-option label="原材料" value="raw" />
            <el-option label="半成品" value="semi" />
            <el-option label="成品" value="finished" />
            <el-option label="包装材料" value="packaging" />
            <el-option label="辅助材料" value="auxiliary" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 120px">
            <el-option label="启用" value="active" />
            <el-option label="禁用" value="inactive" />
          </el-select>
        </el-form-item>
        <el-form-item label="供应商">
          <el-select v-model="searchForm.supplierId" placeholder="请选择供应商" clearable style="width: 150px">
            <el-option
              v-for="supplier in supplierList"
              :key="supplier.id"
              :label="supplier.name"
              :value="supplier.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :icon="Search">
            搜索
          </el-button>
          <el-button @click="resetSearch" :icon="Refresh">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 物料列表 -->
    <div class="table-section">
      <el-table
        :data="materialList"
        v-loading="loading"
        stripe
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="materialCode" label="物料编号" width="150" fixed="left" />
        <el-table-column prop="materialName" label="物料名称" width="200" fixed="left" />
        <el-table-column prop="category" label="分类" width="120">
          <template #default="scope">
            <el-tag :type="getCategoryType(scope.row.category)">
              {{ getCategoryText(scope.row.category) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="specification" label="规格型号" width="150" />
        <el-table-column prop="unit" label="单位" width="80" />
        <el-table-column prop="unitPrice" label="单价" width="100">
          <template #default="scope">
            <span class="price-text">¥{{ scope.row.unitPrice.toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="stockQuantity" label="库存数量" width="100">
          <template #default="scope">
            <span :class="getStockClass(scope.row.stockQuantity, scope.row.minStock)">
              {{ scope.row.stockQuantity }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="minStock" label="最低库存" width="100" />
        <el-table-column prop="supplierName" label="主供应商" width="150" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 'active' ? 'success' : 'danger'">
              {{ scope.row.status === 'active' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="viewMaterial(scope.row)" :icon="View">
              查看
            </el-button>
            <el-button size="small" type="primary" @click="editMaterial(scope.row)" :icon="Edit">
              编辑
            </el-button>
            <el-button size="small" @click="managePrices(scope.row)" :icon="Money">
              价格
            </el-button>
            <el-button size="small" type="danger" @click="deleteMaterial(scope.row)" :icon="Delete">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-section">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 新增/编辑物料对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="70%"
      :before-close="handleDialogClose"
    >
      <el-form
        ref="materialFormRef"
        :model="materialForm"
        :rules="materialRules"
        label-width="120px"
        class="material-form"
      >
        <el-tabs v-model="activeTab">
          <!-- 基本信息 -->
          <el-tab-pane label="基本信息" name="basic">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="物料编号" prop="materialCode">
                  <el-input v-model="materialForm.materialCode" placeholder="请输入物料编号" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="物料名称" prop="materialName">
                  <el-input v-model="materialForm.materialName" placeholder="请输入物料名称" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="物料分类" prop="category">
                  <el-select v-model="materialForm.category" placeholder="请选择分类" style="width: 100%">
                    <el-option label="原材料" value="raw" />
                    <el-option label="半成品" value="semi" />
                    <el-option label="成品" value="finished" />
                    <el-option label="包装材料" value="packaging" />
                    <el-option label="辅助材料" value="auxiliary" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="规格型号" prop="specification">
                  <el-input v-model="materialForm.specification" placeholder="请输入规格型号" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="计量单位" prop="unit">
                  <el-select v-model="materialForm.unit" placeholder="请选择单位" style="width: 100%">
                    <el-option label="个" value="个" />
                    <el-option label="件" value="件" />
                    <el-option label="套" value="套" />
                    <el-option label="公斤" value="公斤" />
                    <el-option label="克" value="克" />
                    <el-option label="米" value="米" />
                    <el-option label="厘米" value="厘米" />
                    <el-option label="升" value="升" />
                    <el-option label="毫升" value="毫升" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="状态" prop="status">
                  <el-select v-model="materialForm.status" placeholder="请选择状态" style="width: 100%">
                    <el-option label="启用" value="active" />
                    <el-option label="禁用" value="inactive" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="物料描述">
              <el-input
                v-model="materialForm.description"
                type="textarea"
                :rows="3"
                placeholder="请输入物料描述"
              />
            </el-form-item>
          </el-tab-pane>

          <!-- 库存信息 -->
          <el-tab-pane label="库存信息" name="inventory">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="当前库存" prop="stockQuantity">
                  <el-input-number
                    v-model="materialForm.stockQuantity"
                    :min="0"
                    :precision="2"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="最低库存" prop="minStock">
                  <el-input-number
                    v-model="materialForm.minStock"
                    :min="0"
                    :precision="2"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="最高库存">
                  <el-input-number
                    v-model="materialForm.maxStock"
                    :min="0"
                    :precision="2"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="安全库存">
                  <el-input-number
                    v-model="materialForm.safeStock"
                    :min="0"
                    :precision="2"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="存储位置">
                  <el-input v-model="materialForm.storageLocation" placeholder="请输入存储位置" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="保质期(天)">
                  <el-input-number
                    v-model="materialForm.shelfLife"
                    :min="0"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>

          <!-- 价格信息 -->
          <el-tab-pane label="价格信息" name="price">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="标准单价" prop="unitPrice">
                  <el-input-number
                    v-model="materialForm.unitPrice"
                    :min="0"
                    :precision="2"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="成本价格">
                  <el-input-number
                    v-model="materialForm.costPrice"
                    :min="0"
                    :precision="2"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="最低售价">
                  <el-input-number
                    v-model="materialForm.minPrice"
                    :min="0"
                    :precision="2"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="最高售价">
                  <el-input-number
                    v-model="materialForm.maxPrice"
                    :min="0"
                    :precision="2"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="价格备注">
              <el-input
                v-model="materialForm.priceRemark"
                type="textarea"
                :rows="2"
                placeholder="请输入价格备注"
              />
            </el-form-item>
          </el-tab-pane>

          <!-- 供应商信息 -->
          <el-tab-pane label="供应商信息" name="supplier">
            <el-form-item label="主供应商" prop="supplierId">
              <el-select v-model="materialForm.supplierId" placeholder="请选择主供应商" style="width: 100%">
                <el-option
                  v-for="supplier in supplierList"
                  :key="supplier.id"
                  :label="supplier.name"
                  :value="supplier.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="备用供应商">
              <el-select
                v-model="materialForm.backupSuppliers"
                multiple
                placeholder="请选择备用供应商"
                style="width: 100%"
              >
                <el-option
                  v-for="supplier in supplierList"
                  :key="supplier.id"
                  :label="supplier.name"
                  :value="supplier.id"
                />
              </el-select>
            </el-form-item>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="采购周期(天)">
                  <el-input-number
                    v-model="materialForm.purchaseCycle"
                    :min="1"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="最小采购量">
                  <el-input-number
                    v-model="materialForm.minPurchaseQty"
                    :min="1"
                    :precision="2"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="供应商备注">
              <el-input
                v-model="materialForm.supplierRemark"
                type="textarea"
                :rows="2"
                placeholder="请输入供应商相关备注"
              />
            </el-form-item>
          </el-tab-pane>
        </el-tabs>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveMaterial" :loading="saving">
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 物料详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="物料详情" width="60%">
      <div class="material-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="物料编号">{{ currentMaterial.materialCode }}</el-descriptions-item>
          <el-descriptions-item label="物料名称">{{ currentMaterial.materialName }}</el-descriptions-item>
          <el-descriptions-item label="分类">
            <el-tag :type="getCategoryType(currentMaterial.category)">
              {{ getCategoryText(currentMaterial.category) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="规格型号">{{ currentMaterial.specification }}</el-descriptions-item>
          <el-descriptions-item label="计量单位">{{ currentMaterial.unit }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="currentMaterial.status === 'active' ? 'success' : 'danger'">
              {{ currentMaterial.status === 'active' ? '启用' : '禁用' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="标准单价">¥{{ currentMaterial.unitPrice?.toFixed(2) }}</el-descriptions-item>
          <el-descriptions-item label="当前库存">{{ currentMaterial.stockQuantity }}</el-descriptions-item>
          <el-descriptions-item label="最低库存">{{ currentMaterial.minStock }}</el-descriptions-item>
          <el-descriptions-item label="主供应商">{{ currentMaterial.supplierName }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ currentMaterial.createTime }}</el-descriptions-item>
          <el-descriptions-item label="物料描述">{{ currentMaterial.description || '无' }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>

    <!-- 价格管理对话框 -->
    <el-dialog v-model="priceDialogVisible" title="价格管理" width="50%">
      <div class="price-management">
        <div class="price-header">
          <span>物料：{{ currentMaterial.materialName }}</span>
          <el-button size="small" type="primary" @click="addPriceRecord" :icon="Plus">
            新增价格记录
          </el-button>
        </div>
        <el-table :data="priceHistory" border style="width: 100%">
          <el-table-column prop="effectiveDate" label="生效日期" width="120" />
          <el-table-column prop="price" label="价格" width="100">
            <template #default="scope">
              <span>¥{{ scope.row.price.toFixed(2) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="priceType" label="价格类型" width="100" />
          <el-table-column prop="remark" label="备注" />
          <el-table-column label="操作" width="100">
            <template #default="scope">
              <el-button size="small" type="danger" @click="deletePriceRecord(scope.$index)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Download,
  Upload,
  Search,
  Refresh,
  View,
  Edit,
  Delete,
  Money
} from '@element-plus/icons-vue'

// 响应式数据
const loading = ref(false)
const saving = ref(false)
const dialogVisible = ref(false)
const detailDialogVisible = ref(false)
const priceDialogVisible = ref(false)
const materialFormRef = ref()
const activeTab = ref('basic')

// 搜索表单
const searchForm = reactive({
  materialName: '',
  materialCode: '',
  category: '',
  status: '',
  supplierId: ''
})

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 物料列表
const materialList = ref([])
const selectedMaterials = ref([])
const currentMaterial = ref({})
const supplierList = ref([])
const priceHistory = ref([])

// 物料表单
const materialForm = reactive({
  id: null,
  materialCode: '',
  materialName: '',
  category: '',
  specification: '',
  unit: '',
  status: 'active',
  description: '',
  stockQuantity: 0,
  minStock: 0,
  maxStock: 0,
  safeStock: 0,
  storageLocation: '',
  shelfLife: 0,
  unitPrice: 0,
  costPrice: 0,
  minPrice: 0,
  maxPrice: 0,
  priceRemark: '',
  supplierId: '',
  backupSuppliers: [],
  purchaseCycle: 7,
  minPurchaseQty: 1,
  supplierRemark: ''
})

// 表单验证规则
const materialRules = {
  materialCode: [
    { required: true, message: '请输入物料编号', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  materialName: [
    { required: true, message: '请输入物料名称', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择物料分类', trigger: 'change' }
  ],
  specification: [
    { required: true, message: '请输入规格型号', trigger: 'blur' }
  ],
  unit: [
    { required: true, message: '请选择计量单位', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ],
  stockQuantity: [
    { required: true, message: '请输入当前库存', trigger: 'blur' }
  ],
  minStock: [
    { required: true, message: '请输入最低库存', trigger: 'blur' }
  ],
  unitPrice: [
    { required: true, message: '请输入标准单价', trigger: 'blur' }
  ],
  supplierId: [
    { required: true, message: '请选择主供应商', trigger: 'change' }
  ]
}

// 计算属性
const dialogTitle = computed(() => {
  return materialForm.id ? '编辑物料' : '新增物料'
})

// 方法
const getCategoryText = (category) => {
  const categoryMap = {
    raw: '原材料',
    semi: '半成品',
    finished: '成品',
    packaging: '包装材料',
    auxiliary: '辅助材料'
  }
  return categoryMap[category] || category
}

const getCategoryType = (category) => {
  const typeMap = {
    raw: 'primary',
    semi: 'warning',
    finished: 'success',
    packaging: 'info',
    auxiliary: 'danger'
  }
  return typeMap[category] || ''
}

const getStockClass = (current, min) => {
  if (current <= min) {
    return 'stock-low'
  } else if (current <= min * 1.5) {
    return 'stock-warning'
  }
  return 'stock-normal'
}

const loadMaterialList = async () => {
  loading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 模拟数据
    const mockData = [
      {
        id: 1,
        materialCode: 'MAT001',
        materialName: '处理器芯片',
        category: 'raw',
        specification: 'A15',
        unit: '个',
        unitPrice: 500.00,
        stockQuantity: 150,
        minStock: 50,
        maxStock: 500,
        safeStock: 80,
        supplierId: 1,
        supplierName: '芯片科技有限公司',
        status: 'active',
        createTime: '2024-01-15 10:30:00',
        description: '高性能处理器芯片，用于智能手机'
      },
      {
        id: 2,
        materialCode: 'MAT002',
        materialName: '内存条',
        category: 'raw',
        specification: '8GB DDR4',
        unit: '个',
        unitPrice: 200.00,
        stockQuantity: 30,
        minStock: 50,
        maxStock: 300,
        safeStock: 70,
        supplierId: 2,
        supplierName: '内存技术公司',
        status: 'active',
        createTime: '2024-01-16 14:20:00',
        description: '高速内存条，8GB容量'
      },
      {
        id: 3,
        materialCode: 'MAT003',
        materialName: '屏幕',
        category: 'raw',
        specification: '6.1寸OLED',
        unit: '个',
        unitPrice: 300.00,
        stockQuantity: 80,
        minStock: 40,
        maxStock: 200,
        safeStock: 60,
        supplierId: 3,
        supplierName: '显示技术有限公司',
        status: 'active',
        createTime: '2024-01-17 09:15:00',
        description: 'OLED高清屏幕，6.1寸'
      },
      {
        id: 4,
        materialCode: 'MAT004',
        materialName: '包装盒',
        category: 'packaging',
        specification: '标准包装',
        unit: '个',
        unitPrice: 5.00,
        stockQuantity: 1000,
        minStock: 200,
        maxStock: 2000,
        safeStock: 300,
        supplierId: 4,
        supplierName: '包装材料公司',
        status: 'active',
        createTime: '2024-01-18 16:45:00',
        description: '产品标准包装盒'
      },
      {
        id: 5,
        materialCode: 'MAT005',
        materialName: '螺丝',
        category: 'auxiliary',
        specification: 'M2*5mm',
        unit: '个',
        unitPrice: 0.10,
        stockQuantity: 5000,
        minStock: 1000,
        maxStock: 10000,
        safeStock: 1500,
        supplierId: 5,
        supplierName: '五金配件公司',
        status: 'active',
        createTime: '2024-01-19 11:30:00',
        description: '精密螺丝，用于产品组装'
      }
    ]
    
    materialList.value = mockData
    pagination.total = mockData.length
  } catch (error) {
    ElMessage.error('加载物料列表失败')
  } finally {
    loading.value = false
  }
}

const loadSupplierList = async () => {
  // 模拟供应商数据
  supplierList.value = [
    { id: 1, name: '芯片科技有限公司' },
    { id: 2, name: '内存技术公司' },
    { id: 3, name: '显示技术有限公司' },
    { id: 4, name: '包装材料公司' },
    { id: 5, name: '五金配件公司' },
    { id: 6, name: '电子元件供应商' },
    { id: 7, name: '塑料制品厂' }
  ]
}

const handleSearch = () => {
  pagination.currentPage = 1
  loadMaterialList()
}

const resetSearch = () => {
  Object.assign(searchForm, {
    materialName: '',
    materialCode: '',
    category: '',
    status: '',
    supplierId: ''
  })
  handleSearch()
}

const handleSelectionChange = (selection) => {
  selectedMaterials.value = selection
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  loadMaterialList()
}

const handleCurrentChange = (page) => {
  pagination.currentPage = page
  loadMaterialList()
}

const showAddDialog = () => {
  resetMaterialForm()
  activeTab.value = 'basic'
  dialogVisible.value = true
}

const resetMaterialForm = () => {
  Object.assign(materialForm, {
    id: null,
    materialCode: '',
    materialName: '',
    category: '',
    specification: '',
    unit: '',
    status: 'active',
    description: '',
    stockQuantity: 0,
    minStock: 0,
    maxStock: 0,
    safeStock: 0,
    storageLocation: '',
    shelfLife: 0,
    unitPrice: 0,
    costPrice: 0,
    minPrice: 0,
    maxPrice: 0,
    priceRemark: '',
    supplierId: '',
    backupSuppliers: [],
    purchaseCycle: 7,
    minPurchaseQty: 1,
    supplierRemark: ''
  })
  materialFormRef.value?.clearValidate()
}

const editMaterial = (row) => {
  Object.assign(materialForm, {
    ...row,
    backupSuppliers: row.backupSuppliers || []
  })
  activeTab.value = 'basic'
  dialogVisible.value = true
}

const viewMaterial = (row) => {
  currentMaterial.value = row
  detailDialogVisible.value = true
}

const managePrices = (row) => {
  currentMaterial.value = row
  // 模拟价格历史数据
  priceHistory.value = [
    {
      effectiveDate: '2024-01-01',
      price: row.unitPrice,
      priceType: '标准价',
      remark: '当前价格'
    },
    {
      effectiveDate: '2023-12-01',
      price: row.unitPrice * 0.95,
      priceType: '标准价',
      remark: '上月价格'
    }
  ]
  priceDialogVisible.value = true
}

const deleteMaterial = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除物料 "${row.materialName}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 模拟删除操作
    ElMessage.success('删除成功')
    loadMaterialList()
  } catch {
    // 用户取消删除
  }
}

const saveMaterial = async () => {
  try {
    await materialFormRef.value.validate()
    
    saving.value = true
    
    // 模拟保存操作
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success(materialForm.id ? '更新成功' : '创建成功')
    dialogVisible.value = false
    loadMaterialList()
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    saving.value = false
  }
}

const handleDialogClose = () => {
  materialFormRef.value?.clearValidate()
}

const addPriceRecord = () => {
  priceHistory.value.unshift({
    effectiveDate: new Date().toISOString().split('T')[0],
    price: 0,
    priceType: '标准价',
    remark: ''
  })
}

const deletePriceRecord = (index) => {
  priceHistory.value.splice(index, 1)
}

const exportMaterial = () => {
  ElMessage.success('导出功能开发中')
}

const importMaterial = () => {
  ElMessage.success('导入功能开发中')
}

// 生命周期
onMounted(() => {
  loadMaterialList()
  loadSupplierList()
})
</script>

<style scoped>
.material-management {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.header-left h2 {
  margin: 0 0 5px 0;
  color: #303133;
}

.page-description {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.header-right {
  display: flex;
  gap: 10px;
}

.search-section {
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.table-section {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.pagination-section {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.price-text {
  color: #e6a23c;
  font-weight: bold;
}

.stock-low {
  color: #f56c6c;
  font-weight: bold;
}

.stock-warning {
  color: #e6a23c;
  font-weight: bold;
}

.stock-normal {
  color: #67c23a;
}

.material-form {
  max-height: 60vh;
  overflow-y: auto;
}

.material-detail {
  max-height: 60vh;
  overflow-y: auto;
}

.price-management {
  max-height: 50vh;
  overflow-y: auto;
}

.price-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  font-weight: bold;
}

.dialog-footer {
  text-align: right;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .material-management {
    padding: 10px;
  }
  
  .page-header {
    flex-direction: column;
    gap: 15px;
    text-align: center;
  }
  
  .header-right {
    justify-content: center;
  }
  
  .search-form {
    flex-direction: column;
  }
  
  .search-form .el-form-item {
    margin-bottom: 10px;
  }
}
</style>